package com.imooc.order.converter;

import com.google.gson.Gson;
import com.imooc.order.dataobject.OrderDetail;
import com.imooc.order.dto.OrderDTO;
import com.imooc.order.enums.ResultEnum;
import com.imooc.order.exception.OrderException;
import com.imooc.order.form.CartForm;
import com.imooc.order.form.OrderForm;
import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.List;

/**
 * @author wy
 * @version 1.0
 * @date 2020/3/5 12:10
 * @description
 **/
@Slf4j
public class OrderForm2OrderDTOConverter {

    public static OrderDTO convert(OrderForm orderForm) {
        Gson gson = new Gson();
        OrderDTO orderDTO = new OrderDTO();
        orderDTO.setBuyerName(orderForm.getName());
        orderDTO.setBuyerPhone(orderForm.getPhone());
        orderDTO.setBuyerAddress(orderForm.getAddress());
        orderDTO.setBuyerOpenid(orderForm.getOpenid());

        List<OrderDetail> orderDetailList = new ArrayList<>();

        if (orderForm.getItems().isEmpty()){
            log.error("购物车信息不正确", orderForm.getItems());
            throw new OrderException(ResultEnum.PARAM_ERROR);
        }

        for (CartForm cartForm: orderForm.getItems()) {
            OrderDetail orderDetail = new OrderDetail();
            orderDetail.setProductId(cartForm.getProductId());
            orderDetail.setProductQuantity(cartForm.getProductQuantity());
            orderDetailList.add(orderDetail);
        }
        orderDTO.setOrderDetailList(orderDetailList);
        return orderDTO;
    }
}
